/******************************************************************************
@file:  BusRegister.java
@author Ramesh Anandhan
DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
 ******************************************************************************/
package com.smartc.ui;

import java.util.ArrayList;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.smartc.connection.HttpConnection;
import com.smartc.connection.ParsedLoginData;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class BusRegister extends Activity implements OnClickListener,
		OnItemSelectedListener {

	protected static final String TAG = "BusRegister";

	private final int DIALOG_STATUS = 0x01;
	private final int PROGRESS_DLG = 0x04;

	private Spinner mCity = null;
	private Spinner mLocation = null;
	private Spinner mBPoint = null;
	private EditText mMNumber = null;
	private EditText mEID = null;

	private Button mSubmit = null;

	private String mSelectedCity = null;
	private String mSelectedRoute = null;
	private String mSelectedBPoint = null;
	private String mIdTransportService = null;
	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onCreate()");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bus_register_1);
		mCityConnection = new HttpConnection();
		/*
		 * String domain = getResources().getString(R.string.domain); String
		 * city_query =
		 * getResources().getString(R.string.bus_register_city_query); String
		 * city_url = domain+city_query;
		 * Log.i(TAG,"onCreate city_url:"+city_url); mCityConnection = new
		 * HttpConnection(); mCityConnection.setUrl(city_url);
		 * mCityConnection.AddHandler(mResponse); mCityConnection.Execute();
		 */

		mCity = (Spinner) findViewById(R.id.edit_city);
		mLocation = (Spinner) findViewById(R.id.edit_location);
		mBPoint = (Spinner) findViewById(R.id.edit_bpoint);
		mMNumber = (EditText) findViewById(R.id.edit_mobile);
		mEID = (EditText) findViewById(R.id.edit_eid);

		// mLocation.setEnabled(false);
		// mBPoint.setEnabled(false);

		mCity.setOnItemSelectedListener(this);
		mLocation.setOnItemSelectedListener(new OnItemSelectedListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() position:" + position);

				if (position == 0){
					mSelectedRoute = null;
					String empty[] = new String[0];
					mSelectedBPoint = null;
					mBPoint.setAdapter(new ArrayAdapter(BusRegister.this,
							R.layout.simple_spinner_item, empty));
					mBPoint.setEnabled(false);
					return;
				}
				mSelectedRoute = mResponse.mRoute_List_id.get(--position);

				String domain = getResources().getString(R.string.domain);
				String city_query = getResources().getString(
						R.string.bus_register_bp);
				String city_url = domain + city_query;

				mCityConnection.setUrl(city_url);
				mCityConnection.clearParam();
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() idRoute:" + mSelectedRoute);
				mCityConnection.AddParam("idRoute", mSelectedRoute);
				mCityConnection.Execute();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		mBPoint.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (AccountLogin.DEBUG)
					Log.i(TAG, "onItemSelected() position:" + position);
				if (position == 0){
					mSelectedBPoint = null;
					return;
				}

				mSelectedBPoint = mResponse.mLocation_List_id.get(--position);
				mIdTransportService = mResponse.mIdTransportService_list
						.get(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		mSubmit = (Button) findViewById(R.id.submit_button);
		mSubmit.setOnClickListener(this);
	}

	@Override
	protected void onStart() {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onStart()");
		super.onStart();
		/*
		 * String domain = getResources().getString(R.string.domain); String
		 * city_query =
		 * getResources().getString(R.string.bus_register_city_query); String
		 * city_url = domain+city_query;
		 * Log.i(TAG,"onCreate city_url:"+city_url); mCityConnection = new
		 * HttpConnection(); mCityConnection.setUrl(city_url);
		 * mCityConnection.AddHandler(mResponse); mCityConnection.Execute();
		 */
	}

	@Override
	protected void onStop() {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onStop()");
		super.onStop();
	}

	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {

		switch (id) {
		case DIALOG_STATUS:
			return new AlertDialog.Builder(BusRegister.this).setMessage(
					mResponse._mMessage).setPositiveButton("OK", null).create();
		case PROGRESS_DLG:
			ProgressDialog mDialog = new ProgressDialog(this);
			mDialog.setMessage("Request In progress....");
			mDialog.setIndeterminate(true);
			mDialog.setCancelable(true);
			return mDialog;
		default:
			return super.onCreateDialog(id, args);
		}
	}

	public void onClick(View arg0) {
		int id = arg0.getId();
		switch (id) {
		case R.id.edit_city:
			break;
		case R.id.edit_location:
			break;
		case R.id.edit_bpoint:
			break;
		case R.id.submit_button:
			if(validateInput() == false)
				return;
			String nmContact = mMNumber.getText().toString().trim();
			String domain = getResources().getString(R.string.domain);
			String submit = getResources().getString(
					R.string.bus_register_submit);
			String register_url = domain + submit;
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage idRoute:" + mSelectedRoute);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage idUser:" + ParsedLoginData.mIdUser);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage idTransportService:"
						+ mIdTransportService);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage idBoardingPoint:" + mSelectedBPoint);
			mCityConnection.setUrl(register_url);
			mCityConnection.clearParam();
			mCityConnection.AddParam("idRoute", mSelectedRoute);
			mCityConnection.AddParam("idUser", ParsedLoginData.mIdUser);
			mCityConnection.AddParam("idTransportService", mIdTransportService);
			mCityConnection.AddParam("idBoardingPoint", mSelectedBPoint);
			mCityConnection.AddParam("nmMobileNumber", nmContact);
			mCityConnection.Execute();
			showDialog(PROGRESS_DLG);
			break;
		}
	}

	public class ResponseHandler extends DefaultHandler {

		private boolean mCity = false;
		// private boolean mCityMain = false;
		private boolean idCity = false;

		private boolean mLocation = false;
		// private boolean mLocationMain = false;
		private boolean mTransportService = false;
		private boolean idTransportRoute = false;

		// private boolean mRoute = false;
		private boolean mRouteNm = false;
		private boolean idRoute = false;

		// private boolean mMessages = false;
		private boolean mStatus = false;
		private boolean mMessage = false;

		public ArrayList<String> mCity_List = new ArrayList<String>();
		public ArrayList<String> mCity_Id = new ArrayList<String>();
		public ArrayList<String> mLocation_List = new ArrayList<String>();
		public ArrayList<String> mRoute_List = new ArrayList<String>();
		public ArrayList<String> mRoute_List_id = new ArrayList<String>();
		public ArrayList<String> mIdTransportService_list = new ArrayList<String>();
		public ArrayList<String> mLocation_List_id = new ArrayList<String>();

		public String _mStatus;
		public String _mMessage;

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (this.mCity) {
				mCity_List.add(new String(ch, start, length));
			} else if (this.idCity) {
				mCity_Id.add(new String(ch, start, length));
			} else if (this.mLocation) {
				mLocation_List.add(new String(ch, start, length));
			} else if (this.mRouteNm) {
				mRoute_List.add(new String(ch, start, length));
			} else if (this.idRoute) {
				mRoute_List_id.add(new String(ch, start, length));
			} else if (this.mStatus) {
				_mStatus = new String(ch, start, length);
			} else if (this.mMessage) {
				_mMessage = new String(ch, start, length);
			} else if (this.mTransportService) {
				mIdTransportService_list.add(new String(ch, start, length));
			} else if (this.idTransportRoute) {
				mLocation_List_id.add(new String(ch, start, length));
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if (localName.equals("nmCity")) {
				this.mCity = false;
			} else if (localName.equals("idCity")) {
				this.idCity = false;
			} else if (localName.equals("Cities")) {
				// this.mCityMain = false;
				Message myMessage = new Message();
				myMessage.obj = "CITY";
				handler.sendMessage(myMessage);
			} else if (localName.equals("nmBoardingLocation")) {
				this.mLocation = false;
			} else if (localName.equals("idTransportRoute")) {
				this.idTransportRoute = false;
			} else if (localName.equals("BoardingLocations")) {
				// this.mLocationMain = false;
				Message myMessage = new Message();
				myMessage.obj = "LOCATION";
				handler.sendMessage(myMessage);
			} else if (localName.equals("nmRoute")) {
				this.mRouteNm = false;
			} else if (localName.equals("idRoute")) {
				this.idRoute = false;
			} else if (localName.equals("Routes")) {
				// this.mRoute = false;
				Message myMessage = new Message();
				myMessage.obj = "ROUTE";
				handler.sendMessage(myMessage);
			} else if (localName.equals("Messages")) {
				// this.mMessages = false;
				Message myMessage = new Message();
				myMessage.obj = "STATUS";
				handler.sendMessage(myMessage);
			} else if (localName.equals("status")) {
				this.mStatus = false;
			} else if (localName.equals("message")) {
				this.mMessage = false;
			} else if (localName.equals("idTransportService")) {
				this.mTransportService = false;
			}
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("nmCity")) {
				this.mCity = true;
			} else if (localName.equals("idCity")) {
				this.idCity = true;
			} else if (localName.equals("Cities")) {
				// this.mCityMain = true;
				mCity_List.clear();
				mCity_Id.clear();
				mCity_List.add("select city");
				mLocation_List.clear();
				mRoute_List.clear();
				mRoute_List_id.clear();
				mLocation_List_id.clear();
			} else if (localName.equals("nmBoardingLocation")) {
				this.mLocation = true;
			} else if (localName.equals("idTransportRoute")) {
				this.idTransportRoute = true;
			} else if (localName.equals("BoardingLocations")) {
				// this.mLocationMain = true;
				mLocation_List.clear();
				mLocation_List_id.clear();
				mLocation_List.add("select boarding point");
			} else if (localName.equals("nmRoute")) {
				this.mRouteNm = true;
			} else if (localName.equals("idRoute")) {
				this.idRoute = true;
			} else if (localName.equals("Routes")) {
				mRoute_List.clear();
				mRoute_List_id.clear();
				mRoute_List.add("select route");
				// this.mRoute = true;
			} else if (localName.equals("Messages")) {
				// this.mMessages = true;
			} else if (localName.equals("status")) {
				this.mStatus = true;
			} else if (localName.equals("message")) {
				this.mMessage = true;
			} else if (localName.equals("idTransportService")) {
				this.mTransportService = true;
			}
		}
	}

	private Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage msg:" + (String) msg.obj);
			String loginmsg = (String) msg.obj;
			if (loginmsg.equals("CITY")) {
				int count = mResponse.mCity_List.size();
				String city[] = new String[count];
				for (int i = 0; i < count; i++)
					city[i] = mResponse.mCity_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(BusRegister.this,
						R.layout.simple_spinner_item, city);
				mCity.setAdapter(Adapter);
				mCity.setEnabled(true);
				String empty[] = new String[0];
				mBPoint.setAdapter(new ArrayAdapter(BusRegister.this,
						R.layout.simple_spinner_item, empty));
				mLocation.setAdapter(new ArrayAdapter(BusRegister.this,
						R.layout.simple_spinner_item, empty));
			} else if (loginmsg.equals("LOCATION")) {
				int count = mResponse.mLocation_List.size();
				String city[] = new String[count];
				for (int i = 0; i < count; i++)
					city[i] = mResponse.mLocation_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(BusRegister.this,
						R.layout.simple_spinner_item, city);
				mBPoint.setAdapter(Adapter);
				mBPoint.setEnabled(true);
			} else if (loginmsg.equals("ROUTE")) {
				int count = mResponse.mRoute_List.size();
				String route[] = new String[count];
				for (int i = 0; i < count; i++)
					route[i] = mResponse.mRoute_List.get(i);

				ArrayAdapter Adapter = new ArrayAdapter(BusRegister.this,
						R.layout.simple_spinner_item, route);
				mLocation.setAdapter(Adapter);
				mLocation.setEnabled(true);
			} else if (loginmsg.equals("STATUS")) {
				removeDialog(PROGRESS_DLG);

				showDialog(DIALOG_STATUS);
			}
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onItemSelected() position:" + position);
		if (position == 0){
			String empty[] = new String[0];
			mSelectedRoute = null;
			mSelectedBPoint = null;
			mBPoint.setAdapter(new ArrayAdapter(BusRegister.this,
					R.layout.simple_spinner_item, empty));
			mLocation.setAdapter(new ArrayAdapter(BusRegister.this,
					R.layout.simple_spinner_item, empty));
			mBPoint.setEnabled(false);
			mLocation.setEnabled(false);
			return;
		}
		mSelectedCity = mResponse.mCity_Id.get(--position);

		String domain = getResources().getString(R.string.domain);
		String route_query = getResources().getString(
				R.string.bus_register_city_route);
		String route_url = domain + route_query;

		mCityConnection.setUrl(route_url);
		mCityConnection.clearParam();
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onItemSelected() idCity:" + mSelectedCity);
		mCityConnection.AddParam("idCity", mSelectedCity);
		mCityConnection.Execute();
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onWindowFocusChanged() hasFocus:" + hasFocus);
		if (hasFocus && TransportTabHome.mTabChanged) {
			mCity.setEnabled(false);
			mLocation.setEnabled(false);
			mBPoint.setEnabled(false);
			mSelectedCity = null;
			mSelectedRoute = null;
			mSelectedBPoint = null;
			mIdTransportService = null;
			mMNumber.setText("");
			mEID.setText("");
			TransportTabHome.mTabChanged = false;
			String domain = getResources().getString(R.string.domain);
			String city_query = getResources().getString(
					R.string.bus_register_city_query);
			String city_url = domain + city_query;
			Log.i(TAG, "onWindowFocusChanged city_url:" + city_url);
			mCityConnection.setUrl(city_url);
			mCityConnection.clearParam();
			mCityConnection.AddHandler(mResponse);
			mCityConnection.Execute();
		}
	}

	private boolean validateInput() {
		boolean valid = true;
		String nmContact = mMNumber.getText().toString().trim();
		String eid = mEID.getText().toString().trim();
		if (!(mSelectedCity != null && mSelectedCity.length() > 0)) {
			valid = false;
			Toast.makeText(this, "Select City", Toast.LENGTH_SHORT).show();
		}

		if (!(mSelectedRoute != null && mSelectedRoute.length() > 0)) {
			valid = false;
			Toast.makeText(this, "Select Route", Toast.LENGTH_SHORT).show();
		}
		if (!(mSelectedBPoint != null && mSelectedBPoint.length() > 0)) {
			valid = false;
			Toast.makeText(this, "Select Boarding Point", Toast.LENGTH_SHORT)
					.show();
		}
		
		if (!(eid != null && eid.length() > 0)) {
			valid = false;
			Toast.makeText(this, "Enter Employee Id", Toast.LENGTH_SHORT).show();
		}
		
		//String numStr = "^[0-9]$";
		if (nmContact.length()<10 || nmContact.length()>13/* || nmContact.matches(numStr)==false*/) {
			valid = false;
			Toast.makeText(this, "Enter valid Mobile Number", Toast.LENGTH_SHORT).show();
		}

		return valid;
	}
}
